﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConanLib
{
    public static class HeatMapper
    {
        private const int steps = 255;

        public static System.Drawing.Color MapValue(double val, double min, double max, System.Drawing.Color minColor, System.Drawing.Color maxColor)
        {
            return HeatMapper.MapValue(val, min, max, minColor, maxColor, 255);
        }

        public static System.Drawing.Color MapValue(double val, double min, double max, System.Drawing.Color minColor, System.Drawing.Color maxColor, int alphaChannel)
        {
            if (double.IsNegativeInfinity(min))
                min = double.MinValue;
            if (double.IsPositiveInfinity(max))
                max = double.MaxValue;


            if (max < min)
                throw new ArgumentException("The Min can't be greate than the Max");
            if (double.IsNaN(val))
                return System.Drawing.Color.Transparent;

            double valx = Math.Max(Math.Min(val, max), min);

            double rDiff = maxColor.R - minColor.R;
            double gDiff = maxColor.G - minColor.G;
            double bDiff = maxColor.B - minColor.B;

            double rStep = rDiff / HeatMapper.steps;
            double gStep = gDiff / HeatMapper.steps;
            double bStep = bDiff / HeatMapper.steps;

            double factor = (max - min) / HeatMapper.steps;

            double x = (valx - min) / factor;

            int r = (int)(minColor.R + Math.Floor((double)(rStep * x)));
            int g = (int)(minColor.G + Math.Floor((double)(gStep * x)));
            int b = (int)(minColor.B + Math.Floor((double)(bStep * x)));
   
            System.Drawing.Color c = minColor;
            try
            {
                c = System.Drawing.Color.FromArgb(alphaChannel, r, g, b);
            }
            catch (ArgumentException ae)
            {
                string s = ae.Message;
            }
            return c;
        }


    }
}
